import { FC, useEffect, useRef, useState } from 'react'
import ProForm, { ModalForm, ProFormInstance, ProFormSelect, ProFormText } from '@ant-design/pro-form'
import { Button, message } from 'antd'
import { EnvironmentSetServerDTO } from '@/model/efficient/EnvironmentSetServerDTO'
import { getAllEnvironment } from '@/api/efficient/environment'
import { getByEnvironment } from '@/api/efficient/server'
import { EnvironmentDTO } from '@/model/efficient/EnvironmentDTO'
import { getApplicationServer, applicationSetServer } from '@/api/efficient/application'
import { ApplicationSetServerDTO } from '@/model/efficient/ApplicationSetServerDTO'

interface SetServerParam {
  applicationId: number
}

const ApplicationSetServerForm: FC<SetServerParam> = ({ applicationId }) => {
  const formRef = useRef<ProFormInstance>()
  const [allEnvironment, setAllEnvironment] = useState<Array<EnvironmentDTO>>([])
  // 获取所有环境
  useEffect(() => {
    getAllEnvironment().then((res) => {
      setAllEnvironment(res)
    })
  }, [])

  /**
   * 根据环境id和应用获取服务器
   */
  const getServerByEnvironment = async (visible: boolean) => {
    if (visible) {
      allEnvironment.map(async (environment) => {
        const applicationServerDTOS = await getApplicationServer(applicationId, environment.id)
        const setServerIds = {}
        setServerIds[`serverIds-${environment.id}`] = applicationServerDTOS.map((item) => item.serverId)
        setServerIds[`deployBranch-${environment.id}`] = applicationServerDTOS[0]?.deployBranch
        formRef.current?.setFieldsValue(setServerIds)
      })
    }
  }
  return (
    <div className="application-set-server-form">
      <ModalForm<EnvironmentSetServerDTO>
        formRef={formRef}
        title="设置服务器"
        onVisibleChange={getServerByEnvironment}
        trigger={
          <Button type="link">
            设置服务器
          </Button>
        }
        onFinish={async (values) => {
          const applicationSetServerDTOs:Array<ApplicationSetServerDTO> = []
          Object.keys(values).forEach((item) => {
            const keys = item.split('-')

            let applicationSetServerDTO = applicationSetServerDTOs.find((applicationServer) => applicationServer.environmentId === Number(keys[1]))
            if (applicationSetServerDTO === undefined) {
              applicationSetServerDTO = new ApplicationSetServerDTO()
              applicationSetServerDTO[keys[0]] = values[item]
              applicationSetServerDTO.environmentId = Number(keys[1])
              applicationSetServerDTOs.push(applicationSetServerDTO)
            } else {
              applicationSetServerDTO[keys[0]] = values[item]
            }
          })
          await applicationSetServer(applicationSetServerDTOs, applicationId)
          message.success('设置成功')
          return true
        }}
      >
        {
          allEnvironment.map((environment) => {
            return (
              <ProForm.Group title={environment.name}>
                <ProFormSelect
                  mode="multiple"
                  key={`serverIds-${environment.id}`}
                  name={`serverIds-${environment.id}`}
                  label="服务器"
                  width="md"
                  placeholder="服务器"
                  request={async () => {
                    const serverLists = await getByEnvironment(environment.id)
                    return serverLists.map((item) => {
                      return {
                        label: `${item?.name}  ${(item?.publicIp || item?.privateIp)}`,
                        value: item?.id,
                      }
                    })
                  }}
                />
                <ProFormText
                  hidden
                  key={`deployBranch-${environment.id}`}
                  name={`deployBranch-${environment.id}`}
                  label="部署分支"
                  placeholder="部署分支"
                />
              </ProForm.Group>
            )
          })
        }
      </ModalForm>
    </div>
  )
}

export default ApplicationSetServerForm
